// axios的封装
import axios from 'axios'
import { ElLoading } from 'element-plus'
import router from '@/router'
import Message from '../utils/Message'

const contentTypeForm = 'application/x-www-form-urlencoded;charset=UTF-8' //以文件形式发送参数（默认）
const contentTypeJson = 'application/json'                                //以json形式发送参数

const responseTypeJson = 'json'

let loading = null;
// axios的封装
const instance = axios.create({
    baseURL: '/api',      //请求路径的前缀
    timeout: 30 * 1000,   //请求超时为30秒
});

//请求拦截器
instance.interceptors.request.use(
    (config) => {
        if (config.showLoading) {
            loading = ElLoading.service({
                lock: true,
                text: '加载中......',
                background: 'rgba(0, 0, 0, 0.7)',
            });
        }
        return config;    //必需返回请求信息，否则不会进行请求
    },
    
    (error) => {          //请求异常时  
        if (config.showLoading && loading) {
            loading.close();
        }
        Message.error("请求发送失败");
        return Promise.reject("请求发送失败");
    }
);

//响应拦截器
instance.interceptors.response.use(
    (response) => {
        // 参数：showLoading：等待请求响应时的样式  errorCallback：请求异常时执行的方法  showError：异常处理
        const { showLoading, errorCallback, showError = true, responseType } = response.config;
        //把loading关闭
        if (showLoading && loading) {
            loading.close();
        }
        const responseData = response.data;
        //判断请求的返回类型是否为流
        if (responseType == 'arraybuffer' || responseType == 'blob') {
            return responseData; //无法解析流，直接返回
        }
        //正常请求
        if (responseData.code == 200) {
            console.log("utils/Request.js: 55 --- responseData.code = 200")
            return responseData;
        } else if (responseData.code == 901) {
            //登陆超时
            console.log("utils/Request.js: 59 --- responseData.code = 901")
            router.push("/login?redirectUrl=" + encodeURI(router.currentRoute.value.path));
            return Promise.reject({ showError: false, msg: "登录超时" });
        } else {
            //其他错误
            console.log("utils/Request.js: 64 --- 其他错误")
            if (errorCallback) {
                errorCallback(responseData.message);
            }
            return Promise.reject({ showError: showError, message: responseData.message });
        }
    },
    (error) => {   
        if (error.config.showLoading && loading) {
            loading.close();
        }
        return Promise.reject({ showError: true, message: "网络异常" });
    }
);

//请求接口/封装
const request = (config) => {
    //发送请求时需要的参数
    const { url, params, dataType, showLoading = true, responseType = responseTypeJson } = config;
    let contentType = contentTypeForm;
    let formData = new FormData();    //创建form对象
    //将所有参数封装成formData
    for (let key in params) {    //判断是否为空
        formData.append(key, params[key] == undefined ? "" : params[key]);
    }
    //判断参数是否为json形式（一般为form表单形式）
    if (dataType != null && dataType == 'json') {
        contentType = contentTypeJson;
    }
    let headers = {
        'Content-Type': contentType,
        'X-Requested-With': 'XMLHttpRequest',
    }

    //只定义了一种请求post
    return instance.post(url, formData, {
        onUploadProgress: (event) => {      //上传进度
            if (config.uploadProgressCallback) {   //是否传递了上传进度更新的方法
                config.uploadProgressCallback(event);
            }
        },
        responseType: responseType,
        headers: headers,
        showLoading: showLoading,
        errorCallback: config.errorCallback,
        showError: config.showError
    }).catch(error => {    //当请求出现异常时执行，参数由68行传递
        console.log("utils/Request.js: 111 --- " + error);
        if (error.showError) {
            Message.error(error.message);
        }
        return null;
    });
};

export default request;    //e死婆尔特、滴for   把api返回